package lib.bone.admin.controller.system.listener;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import lib.bone.access.config.cycle.NepuCycle;
import lib.bone.access.constant.ResearchTypeConst;
import lib.bone.access.constant.WorkloadSourceConst;
import lib.bone.access.constant.WorkloadTypeConst;
import lib.bone.access.module.dict.DictServiceCtl;
import lib.bone.access.module.dict.dao.NepuTopicDictDAO;
import lib.bone.access.module.dict.entity.NepuTopicDict;
import lib.bone.access.module.dict.impl.TopicDictServiceImpl;
import lib.bone.admin.controller.system.dto.TopicImportDTO;
import lib.bone.audit.workload.attach.ResearchAttach;
import lib.bone.audit.workload.domain.NepuWorkload;
import lib.bone.audit.workload.service.NepuWorkloadService;
import lib.bone.common.utils.JsonUtil;
import lib.bone.ext.draft.NepuDraft;
import lib.bone.ext.draft.NepuDraftService;
import lib.bone.ext.draft.dto.DraftAddDTO;
import lib.bone.nepudata.domain.dto.topic.NepuTopicAddDTO;
import lib.bone.nepudata.domain.entity.NepuTopic;
import lib.bone.nepudata.service.impl.NepuTopicServiceImpl;
import lib.bone.system.domain.entity.SysUser;
import lib.bone.system.module.iojob.constant.JobStatusConst;
import lib.bone.system.module.iojob.domain.IOJob;
import lib.bone.system.module.iojob.domain.IOLog;
import lib.bone.system.module.iojob.service.IOJobService;
import lib.bone.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Slf4j
public class TopicListener extends AnalysisEventListener<TopicImportDTO> {

    /**
     * 文件父路径
     */
    String fileParentPath;
    /**
     * 周期ID
     */
    String cycleId;
    /**
     * 父周期ID
     */
    String parentCycleId;
    /**
     * 任务ID
     */
    String ioJobId;

    NepuCycle nepuCycle;
    /**
     * 用户服务
     */
    NepuTopicServiceImpl nepuTopicService;

    TopicDictServiceImpl topicDictService;

    SysUserService sysUserService;
    /**
     * 导入导出服务
     */
    IOJobService ioJobService;

    NepuDraftService draftService;

    NepuWorkloadService workloadService;
    /**
     * 操作日志
     */
    List<IOLog> logs = new ArrayList<>();

    DictServiceCtl dictServiceCtl;

    public TopicListener(SysUserService userService, IOJobService ioJobService, NepuTopicServiceImpl nepuTopicService, String cycleId, String parentCycleId, String ioJobId, String fileParentPath, NepuDraftService draftService, TopicDictServiceImpl topicDictService, NepuCycle nepuCycle, DictServiceCtl dictServiceCtl, NepuWorkloadService workloadService) {
        this.sysUserService = userService;
        this.nepuTopicService = nepuTopicService;
        this.ioJobService = ioJobService;
        this.cycleId = cycleId;
        this.parentCycleId = parentCycleId;
        this.ioJobId = ioJobId;
        this.fileParentPath = fileParentPath;
        this.draftService = draftService;
        this.topicDictService = topicDictService;
        this.nepuCycle = nepuCycle;
        this.dictServiceCtl = dictServiceCtl;
        this.workloadService = workloadService;
    }

    public String buildAttach(NepuTopic topic, NepuTopicDict nepuTopicDict) {
        ResearchAttach attach = new ResearchAttach();
        attach.setResearchId(topic.getId());
        attach.setResearchName(topic.getTopicName());
        attach.setDictId(nepuTopicDict.getId());
        attach.setDictName(nepuTopicDict.getTopicType());
        attach.setResearchLevel(nepuTopicDict.getTopicLevel());
        attach.setResearchType(ResearchTypeConst.TOPIC);
        return JsonUtil.obj2String(attach);
    }




    @Override
    public void invoke(TopicImportDTO topicImportDTO, AnalysisContext analysisContext) {

        Optional<NepuTopic> nepuTopicOptional = nepuTopicService.getByTopicCode(topicImportDTO.getTopicCode());
        if (nepuTopicOptional.isPresent()) {
            log.info("{}:纵向课题信息已存在,课题编码:{},创建时间:{}", topicImportDTO.getTopicName(),topicImportDTO.getTopicCode(),nepuTopicOptional.get().getCreatedTime());
            return;
        }
        NepuTopic nepuTopic = new NepuTopic();
        nepuTopic.setCycleId(cycleId);
        nepuTopic.setTopicFunds(topicImportDTO.getTopicFunds());
        nepuTopic.setTopicName(topicImportDTO.getTopicName());
        nepuTopic.setTopicCode(topicImportDTO.getTopicCode());
        nepuTopic.setLeader(topicImportDTO.getLeaderName());


        //查询纵向课题词典类型
        NepuTopicDict nepuTopicDict = new NepuTopicDict();
        if (topicImportDTO.getDict().equals("厅局级重点项目")){
            nepuTopic.setTopicDictId("4028d081809c77c801809c7fce9d0001");
        }else if (topicImportDTO.getDict().equals("省级基金项目")){
            nepuTopic.setTopicDictId("4028d081809c77c801809c95ddc7000d");
        }else {
            nepuTopicDict = topicDictService.getTopicType(topicImportDTO.getDict());
            nepuTopic.setTopicDictId(nepuTopicDict.getId());
        }

        Optional<SysUser> sysUserOp = sysUserService.findByUserName(topicImportDTO.getLeaderCard());
        if (!sysUserOp.isPresent()){
            log.info("用户不存在"+topicImportDTO.getLeaderCard());
            return;
        }
        Long userId = sysUserOp.get().getId();
        nepuTopic.setLeaderId(userId);
        //获取在研时间，转换格式
        String startTime = topicImportDTO.getStartTime();
        String endTime = topicImportDTO.getEndTime();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = null;
        Date endDate = null;
        try {
            endDate = dateFormat.parse(endTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        try {
            startDate = dateFormat.parse(startTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
//        String str = topicImportDTO.getEffectiveMonths();
//        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
//        String[] strs = str.split("-");
//        String str1;
//        str1 = strs[0].replace(".","-").concat("-01");
//        String str2;
//        str2 = strs[1].replace(".","-").concat("-01");
//        //有重合时间，在工作量表中新建
//        Date startDate = null;
//        try {
//            startDate = ft.parse(str1);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
//        Date endDate = null;
//        try {
//            endDate = ft.parse(str2);
//        } catch (ParseException e) {
//            e.printStackTrace();
//        }
        nepuTopic.setStartDate(startDate);
        nepuTopic.setEndDate(endDate);
        nepuTopic.setIsDelay(0);
        nepuTopic.setReceivedFunds(0.0);
        nepuTopic.setTopicFunds(0.0);

        //判断项目的时间段和周期是否有重合时间
        if (endDate.compareTo(nepuCycle.getStartDate()) == -1 ||
                endDate.compareTo(nepuCycle.getStartDate()) == 0) {
            return;
        }
        if (startDate.compareTo(nepuCycle.getEndDate()) == 1 ||
                startDate.compareTo(nepuCycle.getEndDate()) == 0) {
            return;
        }
        if (startDate.compareTo(nepuCycle.getStartDate()) == -1 ||
                startDate.compareTo(nepuCycle.getStartDate()) == 0) {
            startDate = nepuCycle.getStartDate();
        }
        if (endDate.compareTo(nepuCycle.getEndDate()) == -1 ||
                endDate.compareTo(nepuCycle.getEndDate()) == 0) {

        } else {
            endDate = nepuCycle.getEndDate();
        }
        //添加项目成员
        List<String> list = new ArrayList<>();
        if (StrUtil.isNotEmpty(topicImportDTO.getParticipateId1())) {
            list.add(topicImportDTO.getParticipateId1());
        }
        if (StrUtil.isNotEmpty(topicImportDTO.getParticipateId2())) {
            list.add(topicImportDTO.getParticipateId2());
        }
        if (StrUtil.isNotEmpty(topicImportDTO.getParticipateId3())) {
            list.add(topicImportDTO.getParticipateId3());
        }
        if (StrUtil.isNotEmpty(topicImportDTO.getParticipateId4())) {
            list.add(topicImportDTO.getParticipateId4());
        }
        if (StrUtil.isNotEmpty(topicImportDTO.getParticipateId5())) {
            list.add(topicImportDTO.getParticipateId5());
        }
        if (StrUtil.isNotEmpty(topicImportDTO.getParticipateId6())) {
            list.add(topicImportDTO.getParticipateId6());
        }
        if (StrUtil.isNotEmpty(topicImportDTO.getParticipateId7())) {
            list.add(topicImportDTO.getParticipateId7());
        }
        if (StrUtil.isNotEmpty(topicImportDTO.getParticipateId8())) {
            list.add(topicImportDTO.getParticipateId8());
        }
        if (StrUtil.isNotEmpty(topicImportDTO.getParticipateId9())) {
            list.add(topicImportDTO.getParticipateId9());
        }
        if (StrUtil.isNotEmpty(topicImportDTO.getParticipateId10())) {
            list.add(topicImportDTO.getParticipateId10());
        }
        if (StrUtil.isNotEmpty(topicImportDTO.getParticipateId11())) {
            list.add(topicImportDTO.getParticipateId11());
        }
        if (StrUtil.isNotEmpty(topicImportDTO.getParticipateId12())) {
            list.add(topicImportDTO.getParticipateId12());
        }
        if (StrUtil.isNotEmpty(topicImportDTO.getParticipateId13())) {
            list.add(topicImportDTO.getParticipateId13());
        }
        if (StrUtil.isNotEmpty(topicImportDTO.getParticipateId14())) {
            list.add(topicImportDTO.getParticipateId14());
        }
        if (StrUtil.isNotEmpty(topicImportDTO.getParticipateId15())) {
            list.add(topicImportDTO.getParticipateId15());
        }
        if (StrUtil.isNotEmpty(topicImportDTO.getParticipateId16())) {
            list.add(topicImportDTO.getParticipateId16());
        }
        if (StrUtil.isNotEmpty(topicImportDTO.getParticipateId17())) {
            list.add(topicImportDTO.getParticipateId17());
        }
        if (StrUtil.isNotEmpty(topicImportDTO.getParticipateId18())) {
            list.add(topicImportDTO.getParticipateId18());
        }
        if (StrUtil.isNotEmpty(topicImportDTO.getParticipateId19())) {
            list.add(topicImportDTO.getParticipateId19());
        }
        if (StrUtil.isNotEmpty(topicImportDTO.getParticipateId20())) {
            list.add(topicImportDTO.getParticipateId20());
        }
        if (list.size()!=0) {
            //计算工作量
            //数据存入
            List<SysUser> list1 = sysUserService.findByUserNames(list);
            List<Long> idList = new ArrayList<>();
            for (SysUser sysUser : list1) {
                idList.add(sysUser.getId());
            }
            nepuTopic.setUserIdList(idList);
        }
        NepuTopic nepuTopic1 = nepuTopicService.saveOne(nepuTopic);
        NepuWorkload nepuWorkload = new NepuWorkload();
        // 设置工作量来源 -- 申请
        nepuWorkload.setWorkloadSource(WorkloadSourceConst.APPLY);
        // 设置工作量类型 -- 科研工作量
        nepuWorkload.setWorkloadType(WorkloadTypeConst.RESEARCH);
        // 设置获取工作量用户ID
        nepuWorkload.setUserId(userId);
        //获取科研项目Id
        nepuWorkload.setLinkId(nepuTopic1.getId());
        //设置备注信息
        nepuWorkload.setRemark("["+nepuCycle.getCycleName()+"]"+"导入纵向课题");
        //设置工作量可分配
        nepuWorkload.setWorkloadLock(2);
        // 获取工作量所在周期 -- 从科研项目中提取
        nepuWorkload.setCycleId(nepuCycle.getId());
        nepuWorkload.setParentId(nepuCycle.getId());
        Optional<Object> objectOp = dictServiceCtl.getById(nepuTopic1.getTopicDictId(), ResearchTypeConst.TOPIC);
        if (objectOp.isPresent()) {
            BeanUtil.copyProperties(objectOp.get(), nepuTopicDict, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
            // 设置工作量级别
            String level = nepuTopicDict.getTopicLevel();
            nepuWorkload.setWorkloadLevel(level);
            //工作量计算
            long betweenMonth = DateUtil.betweenMonth(startDate, endDate, false) + 1;
            Double workload = nepuTopicDict.getWorkloadMax() * betweenMonth * 1.0 / 12;
            nepuWorkload.setWorkload(workload);
            // 设置使用工作量为 0 用尽标识为 0
            nepuWorkload.setUsedWorkload(0.0);
            nepuWorkload.setUsedUp(0);
            // 设置工作量附加信息
            String attach = buildAttach(nepuTopic1, nepuTopicDict);
            nepuWorkload.setWorkloadAttach(attach);
            // 设置锁等级为 2
            nepuWorkload.setWorkloadLock(2);
            workloadService.saveOne(nepuWorkload);
        }
        System.out.println("实体类保存成功："+nepuTopic1);
        System.out.println("工作量保存成功："+nepuWorkload);
//        if (list.size()!=0){
//            //计算工作量
//            //数据存入
//            List<SysUser> list1 = sysUserService.findByUserNames(list);
//            List<Long> idList = new ArrayList<>();
//            for (SysUser sysUser : list1) {
//                idList.add(sysUser.getId());
//            }
//            nepuTopic.setUserIdList(idList);
//            NepuTopic nepuTopic1 = nepuTopicService.saveOne(nepuTopic);
//            NepuWorkload nepuWorkload = new NepuWorkload();
//            // 设置工作量来源 -- 申请
//            nepuWorkload.setWorkloadSource(WorkloadSourceConst.APPLY);
//            // 设置工作量类型 -- 科研工作量
//            nepuWorkload.setWorkloadType(WorkloadTypeConst.RESEARCH);
//            // 设置获取工作量用户ID
//            nepuWorkload.setUserId(userId);
//            //获取科研项目Id
//            nepuWorkload.setLinkId(nepuTopic1.getId());
//            //设置备注信息
//            nepuWorkload.setRemark("["+nepuCycle.getCycleName()+"]"+"导入纵向课题");
//            //设置工作量可分配
//            nepuWorkload.setWorkloadLock(2);
//            // 获取工作量所在周期 -- 从科研项目中提取
//            nepuWorkload.setCycleId(nepuCycle.getId());
//            nepuWorkload.setParentId(nepuCycle.getId());
//            Optional<Object> objectOp = dictServiceCtl.getById(nepuTopic1.getTopicDictId(), ResearchTypeConst.TOPIC);
//            if (objectOp.isPresent()) {
//                BeanUtil.copyProperties(objectOp.get(), nepuTopicDict, CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
//                // 设置工作量级别
//                String level = nepuTopicDict.getTopicLevel();
//                nepuWorkload.setWorkloadLevel(level);
//                //工作量计算
//                long betweenMonth = DateUtil.betweenMonth(startDate, endDate, false) + 1;
//                Double workload = nepuTopicDict.getWorkloadMax() * betweenMonth * 1.0 / 12;
//                nepuWorkload.setWorkload(workload);
//                // 设置使用工作量为 0 用尽标识为 0
//                nepuWorkload.setUsedWorkload(0.0);
//                nepuWorkload.setUsedUp(0);
//                // 设置工作量附加信息
//                String attach = buildAttach(nepuTopic1, nepuTopicDict);
//                nepuWorkload.setWorkloadAttach(attach);
//                // 设置锁等级为 2
//                nepuWorkload.setWorkloadLock(2);
//                workloadService.saveOne(nepuWorkload);
//            }
//            System.out.println("带参与成员的纵向课题保存成功！"+nepuTopic1+"------"+"信息为："+nepuWorkload);
//
//        }else {
//            NepuTopicAddDTO nepuTopicAddDTO = new NepuTopicAddDTO();
//            BeanUtil.copyProperties(nepuTopic,nepuTopicAddDTO,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
//            nepuTopicAddDTO.setDeptId(Long.parseLong("2"));
//            nepuTopicAddDTO.setDeptName("教务处");
//            //放入草稿
//            NepuDraft nepuDraft = new NepuDraft();
//            nepuDraft.setFormId("纵向课题");
//            nepuDraft.setFormJsonStr(JsonUtil.obj2String(nepuTopicAddDTO));
//            nepuDraft.setUserId(userId);
//            nepuDraft.setStatus(1);
//            draftService.saveOne(nepuDraft);
//            System.out.println("不带参与成员的纵向课题草稿保存成功！"+nepuDraft);
//
//        }


    }


    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        Optional<IOJob> ioJobOp = ioJobService.getById(ioJobId);
        if (!ioJobOp.isPresent()) {
            log.error("导入任务丢失");
            return;
        }
        IOJob ioJob = ioJobOp.get();
        String filePath = fileParentPath+ File.separator+ioJob.getId()+File.separator+"log.xlsx";
        FileUtil.touch(filePath);
        EasyExcel.write(filePath,IOLog.class).sheet("sheet").doWrite(logs);

        ioJob.setJobStatus(JobStatusConst.FINISHED);
        ioJob.setLogFilePath(filePath);
        ioJobService.updateOne(ioJob);
        log.info("纵向课题导入完成");
    }
}
